# -*- coding: utf-8 -*-
# @Time    : 2021/3/26 15:33
# @Author  : Zhangrenjie
# @Email   : zhangrenjie1998@163.com
# @File    : SC_shoping.py
# @Software: PyCharm

# 三乐购物系统
# • 使用系统需要登录验证，进入系统后，输入购物预算信息
# • 用户可以任意查看商品信息和已购买信息
# • 用户根据商品编号购买商品，购买时，检测余额是否够，够就直接扣款，不够就提醒
# • 可随时退出（输入exit），退出后，打印已购买商品和余额
# • 要求：用尽可能友好的方式输出(作业需要提交代码及执行结果截图)
# 封装函数
# {'F00001': {'name':'苹果','price':1.2},
# 'F00002': {'name':'香蕉','price':5.5},}

from decimal import Decimal


# 登陆注册界面
def index():
    print('欢迎使用三创购物'.center(50, '*'))
    print('1.已有用户登陆'.center(50, ' '))
    print('2.注册新用户'.center(50, ' '))
    print('exit 退出系统')
    while True:
        admin_input = input()
        if admin_input == '1':
            login()
        elif admin_input == '2':
            create()
        elif admin_input == 'exit':
            shopping()
            exit()
        else:
            print('请进行正确的操作！')


# 登陆界面
def login():
    i = 1
    while True:
        global username
        if i <= 3:
            username = input('请输入用户名：')
            if username == "exit":
                shopping()
                exit()
            passwd = input('请输入密码：')
            if username in user_list.keys():
                if passwd == user_list[username]['passwd']:
                    print('登陆成功！')
                    menu()
                else:
                    print(f'密码错误！\n请重新登录!\t还有{3 - i}次机会！')
                    continue
            else:
                print(f"用户名不存在！\n请重新登录!\t还有{3 - i}次机会！")
        else:
            exit()
        i += 1


# 用户注册界面
def create():
    username = input("请输入你需注册的用户名：")
    if username == 'exit':
        exit()
    while True:
        password = input("请设置你的账号密码：")
        password2 = input("请再次输入你的账号密码：")
        if password == password2:
            user_list[username] = {'passwd': password, 'money': 0.00}
            with open('record_list.txt', mode='w', encoding='utf-8') as f:
                # 清空文件
                f.truncate()
            print('注册成功！\n请输入 q 返回上一级')
            break
        else:
            print("两次输入的密码不相同，请重新输入！")
    while True:
        user_input = input()
        if user_input == 'q':
            index()
        elif user_input == 'exit':
            shopping()
            exit()
        else:
            print("请进行正确的操作！")


# 主菜单界面
def menu():
    print('欢迎使用三创购物'.center(50, '*'))
    print('1.平台上架商品'.center(50, ' '))
    print('2.查看购物车'.center(50, ' '))
    print('3.查看交易记录'.center(50, ' '))
    print('4.查看余额'.center(48, ' '))
    print('exit 退出系统')
    while True:
        admin_input = input()
        if admin_input == '1':
            goods()
        elif admin_input == '2':
            shopping()
            print('y 提交订单   q 返回上一级\nexit 退出系统')
            admin_input2 = input()
            if admin_input2 == 'q':
                menu()
            elif admin_input2 == 'y':
                money()
            elif admin_input2 == 'exit':
                exit()
        elif admin_input == '3':
            trading_record()
        elif admin_input == '4':
            check_money()
        elif admin_input == 'exit':
            shopping()
            exit()
        else:
            print('请进行正确的操作！')


# 商品界面
def goods():
    # 打印商品
    print("商品编号\t商品名称\t商品价格\t")
    for key, valuse in goods_list.items():
        print(f"{key}\t{valuse['name']}\t\t{valuse['price']}")
    print("如需购买，请输入 y \n返回上一级 请输入 q")
    while True:
        admin_input = input()
        if admin_input == 'y':
            while True:
                admin_input1 = input("请输入你想购买的商品：\n结束购买 q ")
                # 退出系统
                if admin_input1 == 'exit':
                    shopping()
                    exit()
                # 再买爷人就要没了！！！！！！！
                elif admin_input1 == 'q':
                    print('=' * 50)
                    print('购物车'.center(50, ' '))
                    shopping()
                    print('=' * 50)
                    money()
                if admin_input1 in goods_list.keys():
                    while True:
                        admin_input2 = input("请输入你想购买商品的数量：")
                        if admin_input2.isdigit():
                            if admin_input1 not in shopping_list.keys():
                                # 把单品购买信息写入过渡字典
                                mid1 = goods_list[admin_input1]
                                mid = {admin_input1: {'name': mid1['name'],
                                                      'price': mid1['price'],
                                                      'number': int(admin_input2)}}
                                # 加入购物车
                                shopping_list.update(mid)
                                mid.clear()
                                print("添加成功！")
                                break
                            else:
                                number = shopping_list[admin_input1]['number'] + int(admin_input2)
                                shopping_list[admin_input1]['number'] = number
                                break
                        else:
                            print('请输入正确的数字！')
                else:
                    print("请进行正确的操作！")
        elif admin_input == 'exit':
            shopping()
            exit()
        elif admin_input == 'q':
            menu()
        else:
            print("请进行正确的操作！")


# 购物车界面
def shopping():
    num = 0
    global count
    count = 0
    print("商品编号\t商品名称\t商品价格\t购买数量")
    for keys, valuses in shopping_list.items():
        print(f"{keys}\t{valuses['name']}\t\t{valuses['price']}\t\t{valuses['number']}")
        num += valuses['number']
        count += valuses['number'] * Decimal(valuses['price'])
    print('-' * 30)
    print('数量' + ' ' * 20 + str(num))
    print(f'合计{" " * 20}{count:.2f}')


# 充值
def add():
    admin_input2 = input()
    if admin_input2 == 'exit':
        shopping()
        exit()
    elif admin_input2 == 'y':
        user_list[username]['money'] = Decimal(user_list[username]['money'])
        add_money = Decimal(input("请输入充值金额："))
        if add_money == 'exit':
            shopping()
            exit()
        else:
            user_list[username]['money'] += add_money
            print(f"充值成功！\n你现有金额为：{user_list[username]['money']}元")


# 商品添加
def money():
    # 显示用户余额
    admin_money = Decimal(user_list[username]["money"])
    print(f'你的当前余额为：{admin_money}元')
    if count != 0:
        print(f"你的所想购买商品总金额为：{count:.2f}元\n是否提交订单 y\n返回上一级 q")
        while True:
            admin_input = input()
            if admin_input == 'exit':
                shopping()
                exit()
            elif admin_input == 'y':
                if count > user_list[username]["money"]:
                    print("你的当前余额不足，是否充值？  y/n")
                    add()
                    money()
                else:
                    funds = admin_money - count
                    user_list[username]["money"] = round(funds, 2)
                    print(f'交易成功！\n你的剩余金额为：{funds:.2f}元')
                    with open('record_list.txt', mode='a+', encoding='utf-8') as f:
                        for keys, values in shopping_list.items():
                            f.write(f"{keys}\t{values['name']}\t\t{values['price']}\t\t{values['number']}\n")
                    shopping_list.clear()
                    menu()
            elif admin_input == 'q':
                menu()
    else:
        menu()


# 交易记录
def trading_record():
    num = 0
    count1 = 0
    print(f"{'交易记录'.center(50, '=')}\n商品编号\t商品名称\t商品价格\t购买数量")
    with open('record_list.txt', mode='r', encoding='utf-8') as f:
        text = f.read()
        print(text)
    print('-' * 50)
    while True:
        admin_input = input('返回上一级 q\n退出系统 exit')
        if admin_input == 'q':
            menu()
        elif admin_input == 'exit':
            shopping()
            exit()
        else:
            print("操作有误，重新操作！")


# 查看金额界面
def check_money():
    print(f'你的当前余额为：{user_list[username]["money"]}元\n是否充值？   y/n')
    add()
    while True:
        admin_input2 = input("返回上一级 q ")
        if admin_input2 == 'exit':
            shopping()
            exit()
        elif admin_input2 == 'q':
            menu()
        else:
            print("请进行正确操作！")


#################
# 商品
goods_list = {'F00001': {'name': '苹果', 'price': 1.2},
              'F00002': {'name': '苹果', 'price': 2.2},
              'F00003': {'name': '苹果', 'price': 3.2},
              'F00004': {'name': '苹果', 'price': 4.2},
              'F00005': {'name': '苹果', 'price': 5.2}}
# 用户及余额
user_list = {'root': {'passwd': '123456', 'money': 12.50},
             'admin': {'passwd': 'admin', 'money': 3.00}}

# 购物车
shopping_list = {}

# 调用登陆界面
index()

